<script setup>
import { ref , onMounted } from 'vue'
import Map from 'ol/Map'
import View from 'ol/View'
import TileLayer from 'ol/layer/Tile'
import XYZ from 'ol/source/XYZ'
import {defaults as defaultControls, Zoom, ZoomSlider, ZoomToExtent} from 'ol/control'
import { easeOut } from "ol/easing.js";
const map = ref()
const initData = ref({
  zoom: null,
  center: [],
  rotation: null,
})

const initMap = ()=>{
  map.value = new Map({
    target: 'map',
    layers: [
      new TileLayer({
        source: new XYZ({url: "http://t4.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=d30d1c34260f2edc72b25f9985e2fd69"}),
      })
    ],
    controls: defaultControls({
      zoom: false
    }),
    view: new View({
      center: [113.24981689453125, 23.126468438108688], //视图中心位置
      projection: "EPSG:4326", //指定投影,84参考系投影
      zoom: 12,  //缩放到的级别
    })
  })

  initData.value = {
    zoom: map.value.getView().getZoom(),
    center: map.value.getView().getCenter(),
    rotation: map.value.getView().getRotation(),
  }
}

// 缩小
const zoomOut = ()=>{
  const view = map.value.getView()
  const zoom = view.getZoom();
  view.setZoom(zoom - 1);
}

const zoomIn = ()=>{
  const view = map.value.getView()
  const zoom = view.getZoom();
  view.setZoom(zoom + 1);
}

const translate = ()=>{
  const view = map.value.getView()
  //使用proj转换经纬度的坐标为平面坐标
  //let lonLat = fromLonLat([116.36444091796875, 39.91184298474967],'EPSG:4326');
  //console.log(lonLat)
  //设置当前视图的中心位置与缩放级别
  const center = view.getCenter();
  view.setCenter([center[0] + 1, center[1] + 1])
  view.setZoom(12);
}

const rotate = ()=>{
  const view = map.value.getView()
  const rotation = view.getRotation();
  view.animate({
    duration: 1000,
    rotation: rotation + Math.PI / 4
  })
  // view.setRotation(rotation + Math.PI / 4);
}

const reset = ()=>{
  const view = map.value.getView()
  view.setZoom(initData.value.zoom);
  view.setCenter(initData.value.center);
  view.setRotation(initData.value.rotation);
}

onMounted(()=>{
  initMap()
})

</script>

<template>
  <div id="map">
    <div class="MapTool">
      <el-row>
        <el-button type="primary" @click="zoomOut">缩小</el-button>
        <el-button type="success" @click="zoomIn">放大</el-button>
        <el-button type="info" @click="translate">平移</el-button>
        <el-button type="warning" @click="rotate">旋转</el-button>
        <el-button type="danger" @click="reset">复位</el-button>
      </el-row>
    </div>
  </div>
</template>

<style scoped>
#map{
  width: 100%;
  height: 100%;
}
.MapTool {
  position: absolute;
  right: 50px;
  top: 50px;
  z-index: 9999;
}
</style>